package cn.loioi.test.service;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import cn.loioi.test.MainActivity;
import cn.loioi.test.R;

/**
 * (c) Copyright 2016 by
 *
 * @author :yyzh
 * @description : 通知栏服务
 * @package :cn.loioi.test.service
 * @创建时间 :2016/3/30 11:05
 */
public class NotificationService extends Service {
    private static final String TAG = "NotificationService";
    public static final String NOTIFICATION_SEVICE_RECEIVER_FLAG = "cn.loioi.test.NotificationService";
    private static final int NOTIFICATION_ID = 1; // 如果id设置为0,会导致不能设置为前台service

    private boolean isShow = false;//当前是否开启通知栏显示，防止activity跳转时开启通知栏
    private Notification notification;// 通知栏实例
    private NotificationServiceReceiver notificationServiceReceiver = new NotificationServiceReceiver();//生成广播处理

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onCreate() {
        super.onCreate();
        Notification.Builder builder = new Notification.Builder(this);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        builder.setContentIntent(contentIntent);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("前台服务测试");
        builder.setContentText("没有新的消息");
        notification = builder.build();
        // 注册 开启前台显示的广播
        registerReceiver(notificationServiceReceiver, new IntentFilter(NOTIFICATION_SEVICE_RECEIVER_FLAG));   //注册广播
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "关闭状态栏显示");
        stopForeground(isShow);//关闭前台显示
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        stopForeground(isShow);//关闭前台显示
        unregisterReceiver(notificationServiceReceiver);
        super.onDestroy();
    }

    /**
     * 开启通知栏命令广播接收器
     *
     * @author len
     */
    public class NotificationServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "开启状态栏显示");
            startForeground(NOTIFICATION_ID, notification);
            isShow = true;
        }
    }
}
